package com.sgb.kjwl.viewmodel.pick;


import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import androidx.databinding.ObservableField;

import com.chuanglan.shanyan_sdk.OneKeyLoginManager;




import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.swgk.core.base.api.ICallBack;

import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.pick.PickRecordCount;
import com.sgb.kjwl.model.entity.pick.PickSearchTender;
import com.sgb.kjwl.model.entity.pick.TenderAddenduEntity;
import com.sgb.kjwl.model.entity.pick.TenderDetailEntity3;
import com.sgb.kjwl.model.entity.pick.TenderDictEntity3;
import com.sgb.kjwl.model.entity.pick.TenderInfoBasicEntity3;
import com.sgb.kjwl.model.entity.pick.TenderInfoMainEntity3;
import com.sgb.kjwl.model.entity.pick.TenderInquiryType;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.repository.PickRepertory;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickInquireByLetterActivity;
import com.sgb.kjwl.view.ui.activity.pick.TenderDetailsActivity3;
import com.sgb.kjwl.view.ui.activity.self.userInfo.SetPwdActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.dialog.DialogHelper;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TenderDetailsModel3 extends BaseViewModel {
    public ObservableField<TenderInfoMainEntity3> tenderInfoMainEntity3 = new ObservableField<>(new TenderInfoMainEntity3());
    private PickRepertory repertory;
    private TenderDetailsActivity3 activity;
    private Map map;
    private Map map2;
    private int page;

    public TenderDetailsModel3(TenderDetailsActivity3 activity, PickRepertory repertory) {
        this.activity = activity;
        this.repertory = repertory;
    }

    public void editTender(String tenderNo, int isGz) {
        if (map2 == null)
            map2 = new HashMap();
        map2.put("tenderNo", tenderNo);
        DialogHelper.showProgressDialog(activity, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().editTender(map2).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.setTvIsGz(isGz);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void userFocus(String businessNo, boolean isGz, int comType) {
        if (map == null)
            map = new HashMap();
        map.put("businessNo", businessNo);
        map.put("type", 0);
        DialogHelper.showProgressDialog(activity, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().userFocus(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (comType == 0) {
                        activity.setIsGz(isGz);
                    } else {
//                        activity.setZbqyIsGz(isGz);
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //招采招标详情
    public void getPickBidDetailModel(String id) {
        if (map == null)
            map = new HashMap();
        map.put("id", id);
        String localLng = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
        String localLat = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
        map.put("localLng", localLng);
        map.put("localLat", localLat);
        DialogHelper.showProgressDialog(activity, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getPickBidDetail(map).enqueue(new ICallBack<BaseEntity<TenderDetailEntity3<TenderInfoBasicEntity3<TenderDictEntity3>>>>() {
            @Override
            public void onSuccess(BaseEntity<TenderDetailEntity3<TenderInfoBasicEntity3<TenderDictEntity3>>> data) {
                if (data.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    tenderInfoMainEntity3.set(data.getData().getTenderInfoMainEntity3());
                    activity.showPagerView(data.getData());
                } else {
                    if (!TextUtils.isEmpty(data.getMsg())) {
                        MToast.showToast(activity, data.getMsg());
                    }
                }
            }
        });
    }

    //招标补遗-补遗分页列表
    public void tenderingAddendumPage( boolean b, String tenderId) {
        map = new HashMap();
        page = b ? page + 1 : 1;
        map.put("page",page);
        map.put("limit", 20);
        map.put("tenderId", tenderId);
        DialogHelper.showProgressDialog(activity, null, "加载中", 0, true, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().tenderingAddendumPage(map).enqueue(new ICallBack<BaseEntity<PickSearchTender<List<TenderAddenduEntity>>>>() {

            @Override
            public void onSuccess(BaseEntity<PickSearchTender<List<TenderAddenduEntity>>> data) {
                if (data.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    activity.setAddendumData(data.getData().getList());
                } else {
                    if (!TextUtils.isEmpty(data.getMsg())) {
                        MToast.showToast(activity, data.getMsg());
                    }
                    activity.setAddendumData(new ArrayList<>());
                }
            }
        });

    }

    //新增函询分页列表接口
    public void findTenderInquiryPage( boolean b, String markId) {
        map = new HashMap();
        page = b ? page + 1 : 1;
        map.put("pageNum", page);
        map.put("pageSize", 20);
        map.put("markId", markId);
        DialogHelper.showProgressDialog(activity, null, "加载中", 0, true, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().findTenderInquiryPage(map).enqueue(new ICallBack<BaseEntity<ProListEntity<List<TenderInquiryType>>>>() {

            @Override
            public void onSuccess(BaseEntity<ProListEntity<List<TenderInquiryType>>> data) {
                if (data.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    activity.setTenderInquiry(data.getData().getList());
                } else {
                    if (!TextUtils.isEmpty(data.getMsg())) {
                        MToast.showToast(activity, data.getMsg());
                    }
                    activity.setTenderInquiry(new ArrayList<>());
                }
            }
        });

    }


    public void oneKeyLogin(OneKeyLoginEntity oneKeyLoginEntity) {
        DialogHelper.showProgressDialog(activity, null, "登录中", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().oneClickLogin(oneKeyLoginEntity).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<LoginEntity>> call, Response<BaseEntity<LoginEntity>> response) {

                DialogHelper.dismissProgressDialog();
                if (response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    OneKeyLoginManager.getInstance().finishAuthActivity();
                    if (response.body().getData().isNeedRegister()) {
                        Intent intent = new Intent(activity, SetPwdActivity.class);
                        intent.putExtra("mobile", response.body().getData().getPhone());
                        activity.startActivity(intent);
                    } else {
                        //登录成功逻辑
                        loginImModel(response);

                        /*saveUserInfo(response.body().getData());
                        activity.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                        JPushInterface.setAlias(activity, 1, response.body().getData().getPhone());
                        getUserInfo();*/
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //网易IM登陆
    private void loginImModel(Response<BaseEntity<LoginEntity>> response) {
//        NimUIKit.login(new LoginInfo(response.body().getData().getImAccount(), response.body().getData().getImToken()), new RequestCallback<LoginInfo>() {
//            @Override
//            public void onSuccess(LoginInfo param) {
                DialogHelper.dismissProgressDialog();
                SharedPreferenceUtil.getInstance().cleatData();
                saveUserInfo(response.body().getData());
                MToast.showToast(activity, "登录成功");
                activity.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                JPushInterface.setAlias(activity, 1, response.body().getData().getPhone());
                getUserInfo();
//            }
//
//            @Override
//            public void onFailed(int code) {
//                DialogHelper.dismissProgressDialog();
//            }
//
//            @Override
//            public void onException(Throwable exception) {
//                DialogHelper.dismissProgressDialog();
//            }
//        });
    }

    public void getUserInfo() {
        DialogHelper.showProgressDialog(activity, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getData() == null) return;
                if (response.body().getState().equals("ok")) {
                    activity.getUserMsgSucceed(response.body().getData());
                } else {
                    MToast.showToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void checkToken(String tag) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);

        APIManager.getInstance().getShoppingCarAPI().checkToken().enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if ("shopping_car".equals(tag)) {
                        activity.checkTokenView();
                    }else {
                        activity.checkAddTokenView();
                    }
                } else {
                    if (!"Miss_Permission".equals(response.body().getCode())) {
                        activity.toLogin();
                    } else {
                        MToast.showToast(activity, response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    private void saveUserInfo(LoginEntity loginEntity) {
        repertory.saveToken(loginEntity.getToken());
        repertory.saveAccount(loginEntity.getPhone());

//        NimUIKit.setAccount(loginEntity.getImAccount());
//        AVChatKit.setAccount(loginEntity.getImAccount());
        //Preferences.saveUserAccount(loginEntity.getImAccount());
 //       Preferences.saveUserToken(loginEntity.getImToken());
    }

    /**
     * 检查是否允许报名
     */
    public void checkTenderBidApply(String tenderingId) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("tenderingId", tenderingId);
        APIManager.getInstance().getPickAPI().checkTenderBidApply(map).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data == null) return;
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    activity.checkAllowBid("sq");
                } else if (data.getState().equals(APIManager.RESPONSE_FAIL)) {
                    MToast.showToast(activity, data.getMsg());
                }
            }
        });
    }

    public void checkAllowBid(String id) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("id", id);
        APIManager.getInstance().getPickAPI().checkAllowBid(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_FAIL)) {
                    MToast.showToast(activity, response.body().getMsg());
                } else {
                    activity.checkAllowBid("zc");
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void checkAllowApply(String id) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("tenderNo", id);
        APIManager.getInstance().getPickAPI().checkAllowApply(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_FAIL)) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MToast.showToast(activity, response.body().getMsg());
                        }
                    });
                } else {
                    activity.checkAllowBid("zc");
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void findCustomerServiceImAccount(String customerServiceContactsId) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("customerServiceContactsId", customerServiceContactsId);
        APIManager.getInstance().getPickAPI().getfindCustomerServiceImAccount(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_FAIL)) {
//                    MToast.showToast(activity, response.body().getMsg());
                    activity.checkAllowDialog(response.body().getMsg());
                } else {
                    Object data = response.body().getData(); // 接口返回的是String类型
                    String dataIMid = response.body().getData().toString();
                    IMUtils.getInstance().buildSingleTalking(dataIMid);
//                    NimUIKit.startP2PSession(activity, dataIMid);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });

    }

    public void checkAllowTenderQuestion(String tenderNo,int tenderingType) {
        DialogHelper.showProgressDialog(activity, null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("tenderNo", tenderNo);
        APIManager.getInstance().getPickAPI().checkAllowTenderQuestion(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_FAIL)) {
                    activity.checkAllowDialog(response.body().getMsg());
                } else {
                    PickInquireByLetterActivity.start(activity, tenderNo, "activity",tenderingType);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });

    }

    /**
     * 通过标识来获取跳转连接
     */
    public void getStringUrl(String type,String no) {
        DialogHelper.showProgressDialog(activity, null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getUrlSetting(type).enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data == null || data.getState() == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    String url = data.getData().getUrl() + "?id=" + no;
                    Log.e("api","url---"+url);
                    WebViewX5HostActivity.start(activity, url);
                }
            }
        });
    }

    public void getUrlSetting(String id) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getUrlSetting("recruitment").enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    String url = data.getData().getUrl() + "?id=" + id + "&active=";
                    activity.getUrl(url);
                } else {
                    MToast.showToast(activity, data.getMsg());
                }
            }
        });
    }

    public void tenderRecordCount(String tenderingId) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map<String, String> map = new HashMap<>();
        map.put("tenderingId", tenderingId);
        APIManager.getInstance().getPickAPI().tenderRecordCount(map).enqueue(new ICallBack<BaseEntity<PickRecordCount>>() {
            @Override
            public void onSuccess(BaseEntity<PickRecordCount> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    activity.getTenderRecordCount(data.getData());
                } else {
                    MToast.showToast(activity, data.getMsg());
                }
            }
        });
    }
}
